﻿using Kxx_Common.Net;
using Kxx_Common.Tools;
using Kxx_Domain.DNS;
using Kxx_Log.Log;
using Kxx_Save.DNS;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kxx_Task.DNS
{
    public class DNSLoad
    {
        public static string serverName = "DNSBackGroundService";
        private static bool isService;

        #region 初始化
        /// <summary>
        /// 任务即地址初始化
        /// </summary>
        public static void Init(bool isService)
        {
            DNSLoad.isService = isService;
            DNSLog.LogClearTask();

            NativeIPAddressRefreshTask();

            RecordTaskInit(isService);
        }
        #endregion

        #region 解析任务
        private static readonly object objRecordTask = new object();

        private static ObservableCollection<DomainRecordTaskExecModel> recordTaskList;
        public static ObservableCollection<DomainRecordTaskExecModel> RecordTaskList
        {
            get
            {
                if (recordTaskList == null)
                {
                    lock (objRecordTask)
                    {
                        if (recordTaskList == null)
                        {
                            RecordTaskInit(isService);
                        }
                    }
                }
                return recordTaskList;
            }
            set { recordTaskList = value; }
        }

        /// <summary>
        /// 初始化解析任务
        /// </summary>
        private static void RecordTaskInit(bool isService)
        {
            recordTaskList = new ObservableCollection<DomainRecordTaskExecModel>();

            foreach (DomainRecordTaskModel item in BascConfig.DomainRecordTask)
            {
                DomainRecordTaskExecModel model = new DomainRecordTaskExecModel(isService);

                #region 处理值
                CopyHelper.CopyPropertiesTo(item, model);
                #endregion

                recordTaskList.Add(model);
            }

            #region 定时任务
            int taskWaitTime = 6 * 1000;  //60秒

            new Task(() => {
                while (true)
                {
                    BascConfig.Reload();

                    #region 删除
                    for (int i = 0; i < recordTaskList.Count; i++)
                    {
                        try
                        {
                            var model = BascConfig.DomainRecordTask.Where(d => d.TaskNumber == recordTaskList[i].TaskNumber).First();
                            if (model == null)
                            {
                                recordTaskList[i].Dispose();
                                recordTaskList.RemoveAt(i);
                                i--;
                            }
                        }
                        catch { }
                    }
                    #endregion

                    #region 编辑
                    for (int i = 0; i < recordTaskList.Count; i++)
                    {
                        try
                        {
                            var model = BascConfig.DomainRecordTask.Where(d => d.TaskNumber == recordTaskList[i].TaskNumber).First();
                            if (model == null)
                            {
                                recordTaskList[i].Dispose();
                                recordTaskList.RemoveAt(i);
                                i--;
                                continue;
                            }

                            recordTaskList[i].RecordId = model.RecordId;
                            recordTaskList[i].RR = model.RR;
                            recordTaskList[i].Type = model.Type;
                            recordTaskList[i].TaskWaitTime = model.TaskWaitTime;
                            recordTaskList[i].NotifyFrequency = model.NotifyFrequency;
                            recordTaskList[i].IsRun = model.IsRun;
                        }
                        catch { }
                    }
                    #endregion

                    #region 添加
                    foreach (DomainRecordTaskModel item in BascConfig.DomainRecordTask)
                    {
                        try
                        {
                            if (recordTaskList.Where(r => r.TaskNumber == item.TaskNumber).First() == null)
                            {
                                DomainRecordTaskExecModel model = new DomainRecordTaskExecModel(isService);

                                #region 处理值
                                CopyHelper.CopyPropertiesTo(item, model);
                                #endregion

                                recordTaskList.Add(model);
                            }
                        }
                        catch { }
                    }
                    #endregion

                    Thread.Sleep(taskWaitTime);
                }
            }).Start();
            #endregion
        }
        #endregion

        #region 本机IP地址
        /// <summary>
        /// 本机IP地址
        /// </summary>
        public static string NativeIPAddress;

        /// <summary>
        /// 本地IP地址刷新任务
        /// </summary>
        private static void NativeIPAddressRefreshTask()
        {
            int taskWaitTime = 6 * 1000;  //60秒
            new Task(() => {
                WebClientHelper client = new WebClientHelper();
                while (true)
                {
                    try
                    {
                        string getIP = client.Post("http://www.kexiaoxiao.cn:5678/client/getip", "");
                        //刷新本地IP
                        NativeIPAddress = getIP;
                    }
                    catch { }

                    Thread.Sleep(taskWaitTime);
                }
            }).Start();
        }
        #endregion

        #region 服务
        /// <summary>
        /// 是否安装某个服务
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns></returns>
        public static bool ISWindowsServiceInstalled(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == serviceName)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 服务是否正在运行
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns></returns>
        public static bool IsWindowsServiceRunning(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == serviceName)
                    return service.Status == ServiceControllerStatus.Running;
            }
            return false;
        }
        #endregion
    }
}
